/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.anism.API;

import java.util.Date;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.anism.bean.HolidayRequestFacadeLocal;
import org.anism.business.IRequestStatus;
import org.anism.entity.Employee;
import org.anism.entity.HolidayRequest;

/**
 *
 * @author user
 */
@Stateless
public class HolidayInput implements HolidayInputLocal {

    @EJB
    private HolidayRequestFacadeLocal facade;
    @EJB
    private AuthenticationLocal authentication;
    @PersistenceContext(unitName = "Holidays2-ejbPU")
    private EntityManager em;

    @Override
    public Employee authenticate(final String employeeId, final String password) {
        return authentication.authenticate(employeeId, password);
    }

    /**
     * 
     * @param employeeId login de l'employé auquel on attribu le congé
     * @param startDate début du congé
     * @param endDate fin du congé
     * @param type type du congé
     * @return la demande de congé
     */
    @Override
    public HolidayRequest addHolidayRequest(String employeeId, Date startDate, Date endDate, String type) {
        Employee employee = null;
        Query q = em.createNamedQuery("Employee.findByEmployeeId").setParameter("employeeId", employeeId);

        try {
            employee = (Employee) q.getSingleResult();
        } catch (Exception e) {
            return null;
        }

        HolidayRequest holidayRequest = new HolidayRequest();
        holidayRequest.setStartDate(startDate);
        holidayRequest.setEndDate(endDate);
        holidayRequest.setOwner(employee);
        holidayRequest.setType(type);
        holidayRequest.setCurrentStatus(IRequestStatus.REQUEST_STATUS_CREATED);
        
        // TODO : update RequestHistory collection ??

        facade.create(holidayRequest);

        return holidayRequest;
    }
}
